package cn.wolfcode.luowowo.service.impl;


import cn.wolfcode.luowowo.domain.Banner;
import cn.wolfcode.luowowo.query.BannerQuery;
import cn.wolfcode.luowowo.repository.BannerRepository;
import cn.wolfcode.luowowo.service.IBannerService;
import cn.wolfcode.luowowo.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;


@Service
public class BannerServiceImpl implements IBannerService {



    @Autowired
    private BannerRepository bannerRepository;

    @Autowired
    private MongoTemplate template;


    @Override
    public Banner get(String id) {
        return bannerRepository.findById(id).orElse(null);
    }

    @Override
    public List<Banner> list() {
        return bannerRepository.findAll();
    }

    @Override
    public void save(Banner banner) {
        bannerRepository.save(banner);
    }

    @Override
    public void update(Banner banner) {
        bannerRepository.save(banner);
    }

    @Override
    public void delete(String id) {
        bannerRepository.deleteById(id);
    }

    @Override
    public Page<Banner> query(BannerQuery qo) {

        Query query = new Query();

        PageRequest pageable = PageRequest.of(qo.getCurrentPage()-1, qo.getPageSize(), Sort.Direction.DESC, "_id");

        return DBHelper.query(template,Banner.class,query,pageable);
    }

    @Override
    public void saveOrUpdate(Banner banner) {

        if(StringUtils.hasLength(banner.getId())){
            this.update(banner);
        }else{
            this.save(banner);
        }
    }

    @Override
    public void changeHotValue(String id, int hot) {

    }

    @Override
    public List<Banner> queryByTop5ByType(int type) {

        PageRequest pageable = PageRequest.of(0, 5, Sort.Direction.DESC, "sequence");

        return bannerRepository.findByType(type,pageable);
    }


}
